package com.struggle.myrabbitmq.sample.topic;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
//import com.rabbitmq.client.QueueingConsumer;
import com.struggle.myrabbitmq.sample.MyRabbitConstants;
import com.struggle.myrabbitmq.sample.common.RecvUtil;
import com.struggle.myrabbitmq.util.ConnectionUtil;

import java.io.IOException;

/**
 * @className Receive1
 * @Description 主题模式消费者1
 * @Author liuwj3
 * @Date 2019/10/8 0008 上午 10:52
 **/
public class Receive1 {
    public static void main(String[] args) throws IOException, InterruptedException {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();

        // 声明消费队列
        channel.queueDeclare(MyRabbitConstants.QUEUE_NAME_TOPIC_1, false, false, false, null);

        // 消费者也声明一下交换机
        channel.exchangeDeclare(MyRabbitConstants.EXCHANGE_NAME_TOPIC, BuiltinExchangeType.TOPIC);

        // 绑定队列到交换机
        //channel.queueBind(MyRabbitConstants.QUEUE_NAME_TOPIC_1, MyRabbitConstants.EXCHANGE_NAME_TOPIC, "routekey.*");
        channel.queueBind(MyRabbitConstants.QUEUE_NAME_TOPIC_1, MyRabbitConstants.EXCHANGE_NAME_TOPIC, "routekey.#");

        // 同一时刻服务器只会发送一条消息给消费者
        channel.basicQos(1);

        // rabbitmq 3.4.1版本写法
        /*QueueingConsumer consumer = new QueueingConsumer(channel);
        // 手动确认
        channel.basicConsume(MyRabbitConstants.QUEUE_NAME_TOPIC_1, false, consumer);

        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            byte[] body = delivery.getBody();
            String message = new String(body);
            System.out.println(" [Recv1] Received '" + message + "'");
            Thread.sleep(10);

            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }*/

        // rabbitmq 4.x版本后写法
        DeliverCallback callback = RecvUtil.getDeliverCallback(channel, "Recv1", true);
        // false为手动确认
        channel.basicConsume(MyRabbitConstants.QUEUE_NAME_TOPIC_1, false, callback, consumerTag -> {});
    }
}
